import java.util.ArrayList;

public class Engine {
	public Engine() {

	}

	public Move getBestMove(Board board, int depth) {
		Move bestMove = null;
		Double bestScore = -Double.MAX_VALUE;
		Double currentScore;
		ArrayList<Move> possibleMoves = board.getPossibleMoves();
		//ArrayList<Double> scores = new ArrayList<Double>(possibleMoves.size());

		for (int i = 0; i < possibleMoves.size(); i++) {

			Move currentMove = possibleMoves.get(i);

			Board child = new Board(board);
			child.Play(currentMove);
			currentScore = -AlphaBeta(child, -Double.MAX_VALUE,Double.MAX_VALUE, depth);
			//scores.add(i,currentScore);

			if (bestScore < currentScore) {
				bestMove = currentMove;
				bestScore = currentScore;
			}
		}

		return bestMove;
	}

	private Double AlphaBeta(Board board, Double alpha, Double beta, int depth) {
		if (board.isFull() || depth == 0) {
			return board.getEval(board.getCurrentPlayer());
		} else {
			Double best = -Double.MAX_VALUE;
			ArrayList<Move> possibleMoves = board.getPossibleMoves();
			for (Move currentMove : possibleMoves) {
				Board child = new Board(board);
				child.Play(currentMove);
				Double Val = -AlphaBeta(child, -beta, -alpha, depth - 1);
				if (Val > best) {
					best = Val;
					if (best > alpha) {
						alpha = best;
						if (alpha >= beta) {
							return best;
						}
					}
				}

			}
			return best;
		}
	}
}
